<template>
	<main :style="{ backgroundImage: `url(${url})` }">
		<template v-if="words && words.length">
            <div class="header" >
				<div class="left">
					<img alt="" class="back" :src="url1" @click="goBack" />
					<span>{{ name }}</span>
				</div>
				<div class="middle">
					<span :style="{ color: titleColor() }">单词拼写</span>
				</div>
				<div class="right">
					<Progress class="progress" :max="totalWords" :value="currentWordIndex + 1" :progressColor="progressColor()"></Progress>
					<!-- <div class="progress-wrap" v-if="totalWords">
						<progress :class="[`progress-${path}`]" :max="totalWords" :value="currentWordIndex + 1"></progress>
						<span>{{ `${currentWordIndex + 1}/${totalWords}` }}</span>
					</div> -->
				</div>
			</div>
            <div class="article">
				<div v-aspectRatio class="keyboard-box" :style="{ backgroundColor: cardWrapColor() }">
					<div class="boder-box">
						<span v-if="isWordVisible" class="isWordVisible" :style="{ color: promptColor() }" v-html="currentShowWord"></span>
						<span v-else :class="{ underline: displayedWord.length === 0 }" style="white-space: nowrap">
							<span v-for="(letter, index) in currentWord" :key="index" :style="getLetterStyle(index)"
								style="margin-right: 0.2vw">
								{{ /[^a-zA-Z]/g.test(letter) ? letter : (displayedWord[index] || "_") }}
							</span>
						</span>
					</div>
					<div class="letter-box">
						<div v-for="(item, index) in shuffledAlphabet" :key="index"
							:class="[gradeType === 'primary' ? 'letter' : 'letters', { [gradeType === 'primary' ? 'disabled' : 'disableds']: item.disabled ||  letterDisabled}]"
							@click="checkLetter(item.letter, index)">
							{{ item.letter }}
						</div>
					</div>
					<div class="img-box">
						<img :src="urlCPlay" alt="" class="img" @click="playAudio" />
						<img :src="urlPrompt" alt="" class="img" @click="toggleWordVisibility" />
					</div>
					<!-- <div class="music-box">
						<div class="img-box">
							<img src="../../public/assets/music.png" alt="" class="img" @click="playAudio" />
							<img src="../../public/assets/prompt.png" alt="" class="img" @click="toggleWordVisibility" />
						</div>
					</div>
					<div class="alphabet">
						<div class="letter-box">
							<div v-for="(item, index) in shuffledAlphabet" :key="index"
								:class="[gradeType === 'primary' ? 'letter' : 'letters', { [gradeType === 'primary' ? 'disabled' : 'disableds']: item.disabled }]"
								@click="checkLetter(item.letter, index)">
								{{ item.letter }}
							</div>
						</div>
					</div> -->
				</div>
			</div>
			<div class="footer">
				<div class="footer-wrap">
					<div @click.prevent="prevWord"
						class="footer-btn-wrap footer-btn-left-wrap">
						<div class="footer-btn">
							<template v-if="currentWordIndex == 0">
								<img alt="" :src="urlPreGray" style="width: 100%; height: 100%" />
							</template>
							<template v-else>
								<img alt="" :src="urlPre" style="width: 100%; height: 100%" />
							</template>
						</div>
						<span class="footer-btn-title">上一个</span>
					</div>

					<div @click.prevent="nextWord"
						class="footer-btn-wrap  footer-btn-right-wrap">
						<div class="footer-btn">
							<!-- <template v-if="currentWordIndex >= totalWords - 1">
								<img alt="" :src="urlNextGray" style="width: 100%; height: 100%" />
							</template>
							<template v-else>
								<img alt="" :src="urlNext" style="width: 100%; height: 100%" />
							</template> -->
							<img alt="" :src="urlNext" style="width: 100%; height: 100%" />
						</div>
						<span class="footer-btn-title">{{ currentWordIndex >= totalWords - 1 ? '提交': '下一个' }}</span>
					</div>
				</div>
			</div>
		</template>
		<Dialog :open="recordingOpen">
			<div class="dialog-wrap-finished">
				<div class="content">
					<img alt="" src="../public/assets/vocabulary/ty_tb_14_pt@2x.png" />
					<span>你真棒，完成了全部的单词学习。</span>
					<div class="control">
						<button @click="goBack" class="button btn-back"
							:style="{ background: buttonBackColor() }">返回单元</button>
						<button @click="restartGame" class="button btn-agin"
							:style="{ background: buttonAginColor() }">再来一遍</button>
					</div>
				</div>
			</div>
		</Dialog>
	</main>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import Dialog from "../component/dialog/index.vue";
import { getSpellinginterface } from "../api/expression.js";
import Grade from "../utils/grade.js"
import '../css/evaluation.css'
import Progress from "../component/progress/index.vue";

const router = useRouter(); // 获取路由实例
const route = useRoute();
const { id, name } = route.query;

const path = window.gradeId > 61 ? 'middle' : 'primary';
const gradeType = window.gradeId > 61 ? 'middle' : 'primary';

const url = new URL(`../public/assets/vocabulary/${path}/d_bg.png`, import.meta.url).href;
const url1 = new URL(`../public/assets/book/${path}/back.png`, import.meta.url).href;
const urlNext = new URL(`../public/assets/expression/${path}/next.png`, import.meta.url).href;
const urlNextGray = new URL(`../public/assets/expression/${path}/next_gray.png`, import.meta.url).href;
const urlPre = new URL(`../public/assets/expression/${path}/pre.png`, import.meta.url).href;
const urlPreGray = new URL(`../public/assets/expression/${path}/pre_gray.png`, import.meta.url).href;
const urlPrompt = new URL(`../public/assets/expression/${path}/prompt.png`, import.meta.url).href;
const urlCPlay = new URL(`../public/assets/expression/${path}/c_play.png`, import.meta.url).href;

function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
}

// 引入音频文件
const buttonSound = new Audio("assets/audio/prompt/按钮声.mp3");
const errorSound = new Audio("assets/audio/prompt/error.wav");
const completeMusic = new Audio("assets/audio/prompt/jiesuan.mp3"); // 完成音乐
const recordingOpen = ref(false);
const words = ref([]); // 使用 ref 来定义 words
const backgroundDiv = ref(null); // 使用 ref 来引用背景元素
const alphabet = Array.from({ length: 26 }, (_, i) => String.fromCharCode(97 + i)); // a-z 小写字母

const currentWordIndex = ref(0); // 当前单词索引
const currentWord = ref("");
const currentShowWord = ref("");
const shuffledAlphabet = ref([]);
const matchedLetters = ref(new Set());
const isWordVisible = ref(false); // 控制单词的显示状态
const currentMatchIndex = ref(0); // 当前匹配的字母索引
const displayedWord = ref(""); // 用于显示已匹配的字母
const completedWords = ref(1); // 已完成的单词数量，初始为1
const totalWords = ref(0); // 总单词数量
// import { spell } from "../../utils/spell/spell";
let currentAudio = new Audio(); // 当前播放的音频对象

const letterDisabled = ref(false)

const getCurrentWord = () => {
	return words.value[currentWordIndex.value]?.title || ""; // 返回当前单词的 title 属性，确保不为 undefined
};

const playAudio = () => {
	// if (currentAudio) {
	// 	currentAudio.pause(); // 停止当前音频
	// }
	const audioUrl = words.value[currentWordIndex.value]?.url; // 获取当前单词对应的音频 URL
	if (audioUrl) {
		if (!currentAudio.paused) {
			currentAudio.pause();
		}
		currentAudio.src = audioUrl;
		currentAudio.play();
		// currentAudio = new Audio(audioUrl); // 创建 Audio 对象
		// currentAudio.play().catch(error => {
		// 	console.error("音频播放失败:", error); // 捕获播放错误
		// });
	}
};

function updateBackground() {
	if (backgroundDiv.value) {
		// 确保元素存在
		if (gradeType === "primary") {
			backgroundDiv.value.style.backgroundImage = "url('../public/assets/beijing.png')"; // 当变量为小学时的背景图
		} else {
			backgroundDiv.value.style.backgroundImage = "url('../public/assets/middleschool.png')"; // 当变量为初中时的背景图
		}
	}
}

const shuffleAlphabet = word => {
	const letters = word.replace(/[^a-zA-Z]/g, "").split(""); // 保留字母的原始大小写
	const keyboardLetters = [...letters]; // 复制字母

	// 填充剩余字母
	while (keyboardLetters.length < 24) {
		const randomLetter = alphabet[Math.floor(Math.random() * alphabet.length)];
		keyboardLetters.push(randomLetter);
	}

	// 打乱字母顺序
	shuffledAlphabet.value = keyboardLetters
		.sort(() => Math.random() - 0.5)
		.map(letter => ({
			letter: letter, // 保留字母的大小写
			disabled: false,
		}));
};

let completeTimer = null;
const checkLetter = (letter, index) => {
	if (letterDisabled.value) {
		return;
	}
	isWordVisible.value = false;
	// 检查当前字母是否与单词中的对应字母匹配，区分大小写
	if (currentMatchIndex.value < currentWord.value.length && currentWord.value[currentMatchIndex.value] === letter) {
		matchedLetters.value.add(letter); // 添加到已匹配字母集合
		shuffledAlphabet.value[index].disabled = true; // 禁用已匹配的字母
		displayedWord.value += letter; // 更新显示的已匹配字母
		currentMatchIndex.value++; // 移动到下一个字母

		let nextLetter = currentWord.value[currentMatchIndex.value];
		while(/[^a-zA-Z]/g.test(nextLetter)) {
			displayedWord.value += nextLetter; // 更新显示的已匹配字母
			currentMatchIndex.value++; // 移动到下一个字母
			nextLetter = currentWord.value[currentMatchIndex.value];
		}

		// 播放 ButtonSound 音频
		buttonSound.currentTime = 0; // 重置音频播放时间
		buttonSound.play(); // 播放音频

		// 检查是否完成整个单词
		if (currentMatchIndex.value === currentWord.value.length) {
			if (completedWords.value < totalWords.value) {
				completedWords.value++; // 增加已完成的单词数量，确保不超过总单词数
			}
			
			currentAudio.pause(); // 停止当前音频
			completeMusic.play(); // 播放完成音乐
			letterDisabled.value = true;

			// if (currentWordIndex.value === totalWords.value - 1) {
			// 	// 如果是最后一个单词，播放完成音乐
			// 	// completeMusic.play(); // 播放完成音乐
			// 	completeTimer = setTimeout(() => {
			// 		currentAudio.pause(); // 停止当前音频
			// 		recordingOpen.value = true; // 延迟1秒后弹出弹框
			// 		letterDisabled.value = false;
			// 	}, 2000);
			// } else {
			// 	completeTimer = setTimeout(resetGame, 2000); // 1秒后重置
			// 	// resetGame(); // 重置
			// }
			completeTimer = setTimeout(resetGame, 2000); // 1秒后重置

		}
	} else {
		// 播放 error 音频
		errorSound.currentTime = 0; // 重置音频播放时间
		errorSound.play(); // 播放错误音频
	}
};

const resetGame = () => {

	if (currentWordIndex.value >= totalWords.value - 1) {
		recordingOpen.value = true; // 延迟1秒后弹出弹框
		return;
	}

	letterDisabled.value = false;
	currentMatchIndex.value = 0; // 重置当前匹配字母索引
	displayedWord.value = ""; // 清空已匹配字母显示
	matchedLetters.value.clear(); // 清空已匹配字母集合

	currentWordIndex.value++; // 移动到下一个单词
	let word = getCurrentWord();
	currentWord.value = word.replace(/<[^>]*>/g, ''); // 获取当前单词
	currentShowWord.value = word;
	shuffleAlphabet(currentWord.value); // 根据当前单词生成字母
	playAudio(); // 播放新单词的音频

	// // 更新当前单词索引
	// if (currentWordIndex.value < totalWords.value - 1) {
	// 	currentWordIndex.value++; // 移动到下一个单词
	// 	currentWord.value = getCurrentWord(); // 获取新的单词
	// 	shuffleAlphabet(currentWord.value); // 根据当前单词生成字母
	// 	playAudio(); // 播放新单词的音频
	// } else {
	// 	currentWordIndex.value = totalWords.value - 1; // 如果到达最后一个单词，则保持在最后一个
	// 	currentWord.value = getCurrentWord(); // 获取新的单词
	// 	shuffleAlphabet(currentWord.value); // 根据当前单词生成字母
	// }
};

let timer = null;
const toggleWordVisibility = () => {
	isWordVisible.value = !isWordVisible.value; // 切换单词的显示状态

	if (isWordVisible.value) {
		if (timer) {
			clearTimeout(timer);
			timer = null;
		}
		timer = setTimeout(() => {
			isWordVisible.value = false;
		}, 3000);
	}
};

const goBack = () => {
	router.go(-1);
	currentAudio.pause(); // 停止当前音频
	recordingOpen.value = false;
};

const restartGame = () => {

	letterDisabled.value = false;
	currentMatchIndex.value = 0; // 重置当前匹配字母索引
	displayedWord.value = ""; // 清空已匹配字母显示
	matchedLetters.value.clear(); // 清空已匹配字母集合

	currentWordIndex.value = 0; // 重置为第一个单词
	completedWords.value = 1; // 重置已完成的单词数量为1
	initializeGame(); // 重新初始化
	recordingOpen.value = false;
};

const initializeGame = () => {
	let word = getCurrentWord();
	currentWord.value = word.replace(/<[^>]*>/g, ''); // 获取当前单词
	currentShowWord.value = word;
	shuffleAlphabet(currentWord.value); // 根据当前单词生成字母
	isWordVisible.value = false; // 初始化时不显示单词
	matchedLetters.value.clear(); // 清空已匹配字母集合
	currentMatchIndex.value = 0; // 重置当前匹配字母索引
	displayedWord.value = ""; // 清空已匹配字母显示
	playAudio(); // 播放第一个单词的音频
};

const progressWidth = computed(() => {
	return `${(completedWords.value / totalWords.value) * 100}%`; // 计算进度条宽度
});

// 获取字母样式
const getLetterStyle = index => {
	if (index < displayedWord.value.length) {
		return { textDecoration: "none", color: "black" }; // 已匹配的字母
	}
	return { textDecoration: "none", color: "black" }; // 未匹配的字母
};

// 上一个单词
const prevWord = () => {
	if (currentWordIndex.value <= 0) {
		return;
	}
	if (completeTimer) {
		clearTimeout(completeTimer);
		completeTimer = null;
	}
	letterDisabled.value = false;
	isWordVisible.value = !isWordVisible.value; // 切换单词的显示状态
	initializeGame();
	if (currentWordIndex.value > 0) {
		currentWordIndex.value--; // 移动到上一个单词
		let word = getCurrentWord();
		currentWord.value = word.replace(/<[^>]*>/g, ''); // 获取当前单词
		currentShowWord.value = word;
		shuffleAlphabet(currentWord.value); // 根据当前单词生成字母
		playAudio(); // 播放当前单词的音频
		completedWords.value--; // 减少已完成的单词数量，确保不低于1
		if (completedWords.value < 1) {
			completedWords.value = 1; // 确保不低于1
		}
	}
};

// 下一个单词
const nextWord = () => {
	if (currentWordIndex.value >= totalWords.value - 1) {
		currentAudio.pause(); // 停止当前音频
		completeMusic.pause();
		errorSound.pause();
		recordingOpen.value = true; // 延迟1秒后弹出弹框
		return;
	}
	if (completeTimer) {
		clearTimeout(completeTimer);
		completeTimer = null;
	}
	letterDisabled.value = false;
	isWordVisible.value = !isWordVisible.value; // 切换单词的显示状态
	initializeGame();
	if (currentWordIndex.value < totalWords.value - 1) {
		currentWordIndex.value++; // 移动到下一个单词
		let word = getCurrentWord();
		currentWord.value = word.replace(/<[^>]*>/g, ''); // 获取当前单词
		currentShowWord.value = word;
		shuffleAlphabet(currentWord.value); // 根据当前单词生成字母
		playAudio(); // 播放当前单词的音频
		if (completedWords.value < totalWords.value) {
			completedWords.value++; // 增加已完成的单词数量，确保不超过总单词数
		}
	}
};

// 控制上一个按钮的可用状态
const isPrevDisabled = computed(() => currentWordIndex.value === 0);

// 控制下一个按钮的可用状态
const isNextDisabled = computed(() => currentWordIndex.value === totalWords.value - 1);

const getSpellingDetail = async () => {
	try {
		const res = await getSpellinginterface(id);
		console.log("res", res);
		if (res.data && res.data.length) {
			words.value = shuffleArray(res.data);
			totalWords.value = words.value.length; // 更新总单词数量
			console.log(words.value, "words.valuewords.value");
			initializeGame(); // 数据获取成功后初始
		}
	} catch (error) {
		console.error(error); // 打印错误信息
	}
};

// 在组件挂载时初始化
onMounted(() => {
	initializeGame();
	// updateBackground(); // 在 mounted 时更新背景
	getSpellingDetail();
});

onUnmounted(() => {
	if (completeTimer) {
		clearTimeout(completeTimer);
		completeTimer = null;
	}
	if (timer) {
		clearTimeout(timer);
		timer = null;
	}
});

const titleColor = () => {
	if (path == 'middle') {
		return '#222'
	} else {
		return '#854B22'
	}
}
const buttonBackColor = () => {
    if (path == 'middle') {
        return '#FFA53E'
    } else {
        return 'linear-gradient(to bottom, #FFC55E, #ED9900)'
    }
}

const buttonAginColor = () => {
    if (path == 'middle') {
        return '#1E4BA6'
    } else {
        return 'linear-gradient(to bottom, #85D389, #61BD66)'
    }
}

const progressColor = () => {
    if (path == 'middle') {
        return '#1E4BA6'
    } else {
        return '#FFB530'
    }
}

const promptColor = () => {
	if (path == 'middle') {
        return '#4392F4'
    } else {
        return '#f5b956'
    }
}

const cardWrapColor = () => {
    if (path == 'middle') {
        return '#fff'
    } else {
        return '#FFFAF1'
    }
}

</script>

<style scoped>
.keyboard-box {
	background-color: #FFFAF1;
	border-radius: 1rem;
	width: 70%;
	/* height: 100%; */
	box-sizing: border-box;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: space-around;
	position: relative;
	padding: 2% 2%;
    /* margin: 3.5rem 0 3.5rem 0; */
}

.boder-box {
	/* width: 653px; */
	/* height: 20%; */
	/* margin-top: 51px; */
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 2.4rem;
	font-family: 'text-en';
}

.img-box {
	display: flex;
	flex-direction: column;
	justify-content: space-between;
	position: absolute;
	right: 2%;
	top: 6%;
	/* height: 5rem; */
}

.img-box .img {
	cursor: pointer;
	width: 2rem;
	float: right;
	/* margin-top: 2rem; */
}

.img-box .img:nth-last-child(1) {
	margin-top: 1rem;
}

.letter-box {
	display: flex;
	align-items: center;
	flex-wrap: wrap;
	width: 32rem;
	/* justify-content: space-between; */
	margin-left: 0.5rem;
	/* margin-top: 3rem;
	margin-bottom: 3rem; */
	font-family: 'text-en';
}


/* .letter-box::after {
	content: '';
	flex: auto;
	width: 4vw; 
} */

/* .letter:not(:nth-child(8n + 1)) {
	margin-right: 1rem;
	margin-bottom: 1rem;
} */

.letter {
	width:  3.5rem;
	height:  3.5rem;
	background-color: #FFF1D7;
	color: #FFB530;
	display: flex;
	align-items: center;
	justify-content: center;
	cursor: pointer;
	margin-right: 0.5rem;
	margin-bottom: 0.5rem;
	/* 设置鼠标光标为小手图标 */
	border-radius: 0.5rem;
	font-size: 2rem;
}

.letters {
	width:  3.5rem;
	height:  3.5rem;
	background-color: #edf2ff;
	color: #4392f4;
	display: flex;
	align-items: center;
	justify-content: center;
	cursor: pointer;
	/* 设置鼠标光标为小手图标 */
	margin-right: 0.5rem;
	margin-bottom: 0.5rem;
	/* 设置鼠标光标为小手图标 */
	border-radius: 0.5rem;
	font-size: 2rem;
}

/* .school {
	width: 60px;
	height: 60px;
	background-color: #edf2ff;
	display: flex;
	align-items: center;
	justify-content: center;
	cursor: pointer;
	border-radius: 10px;
	margin-right: 38px;
	margin-bottom: 10px;
} */

/* .alphabet {
	display: flex;
	justify-content: center;
	align-items: center;
	margin-top: 20px;
} */

.disabled {
	background-color: #61BD66;
	color: #fff;
	/* 灰色背景 */
	cursor: not-allowed;
	/* 禁用光标 */
}

.disableds {
	background-color: #4392f4;
	/* 灰色背景 */
	color: #fff;
	cursor: not-allowed;
	/* 禁用光标 */
}

.letterTyle {
	background-color: #4392f4;
	/* 灰色背景 */
	cursor: not-allowed;
	/* 禁用光标 */
}

.isWordVisible {
	color: #f5b956;
}


.btn-box {
	display: flex;
}

/* .return {
	width: 222px;
	height: 66px;
	background-color: #ed9900;
	font-size: 22px;
	color: #ffffff;
	border-radius: 15px;
	display: flex;
	align-items: center;
	justify-content: center;
} */

/* .Onceagain {
	width: 222px;
	height: 66px;
	background-color: #44a74a;
	font-size: 22px;
	color: #ffffff;
	border-radius: 15px;
	display: flex;
	align-items: center;
	justify-content: center;
} */

/* .title-box {
	font-size: 34px;
	color: #ffffff;
	margin: 10px 0 10px 0;
} */

.underline {
	text-decoration: none;
	color: black;
	white-space: nowrap;
	/* 确保文本不换行 */
	overflow: hidden;
	/* 隐藏溢出内容 */
	text-overflow: ellipsis;
	/* 如果文本过长，显示省略号 */
	display: inline-block;
	/* 使元素成为行内块元素 */
}

/* @media (min-width: 1441px) {
	.word {
		font-size: 44px;
		color: #854b22;
		margin-right: -3%;
	}
	.muis {
		position: absolute;
		right: 10px;
		top: -3px;
		color: #333;
	}
	.btn-box {
		width: 50%;
		display: flex;
		justify-content: center;
		justify-content: space-between;
		margin-top: 90px;
	}
	.keyboard-box {
		position: relative;
		width: 1040px;
		height: 550px;
		background: #fffaf1;
		border-radius: 40px;
		display: flex;
		flex-direction: column;
	}
} */
/* @media (min-width: 1281px) and (max-width: 1440px) {
	.right {
		width: 40%;
		height: 570px;
		background: #fbfbfb;
		border-radius: 40px;
		overflow: scroll;
	}
	.audio {
		width: 950px;
	}
	.word {
		font-size: 44px;
		color: #854b22;
		margin-right: -6%;
	}
} */

</style>

